<template>
  <!--  提现-->
  <div class="withdraw-cash" :style="{ paddingTop: capsuleTop + 'px' }">
    <Return />
    <div class="withdraw-cash-card">
      <div class="card-title">可提现金额</div>
      <div class="card-priceStr">
        <div class="priceStr-title">￥</div>
        <div class="priceStr-value">{{ formatMoney(Number(fundInfo.availableFeeStr)) }}</div>
      </div>

      <!-- 新增：冻结金额 -->
      <div class="card-freeze">
        <span class="freeze-label">冻结金额：</span>
        <span class="freeze-amount">￥{{ formatMoney(Number(fundInfo.freezeFeeStr)) }}</span>
      </div>

      <div class="card-btn">
        <div class="card-btn-left">提现最低额度为{{ minWithdrawAmount }}元</div>
        <!-- <div class="card-btn-right" @click="goToAccountManage">收款账户管理</div> -->
      </div>
    </div>
    <div class="page-line"></div>
    <div class="withdraw-cash-tx">
      <div class="tx-title">
        <div class="tx-title-left">提款金额 <span class="tx-title-left-value">￥{{ formatMoney(Number(fundInfo.availableFeeStr)) }}</span>
        </div>
        <div class="tx-title-right" @click="withdrawAll">全部提现</div>
      </div>
      <div class="feedback-value">
        <input type="digit" v-model="withdrawAmountInput" placeholder="请输入提现金额" @input="handleAmountInput"
          @blur="validateAmount">
      </div>
      <div v-if="amountError" class="amount-error">{{ amountError }}</div>
    </div>
    <div class="page-line"></div>
    <div class="withdraw-cash-form">
      <div class="title">选择提款的方式</div>
      <div class="form-item" @click="selectPaymentMethod('wechat')">
        <img src="../static/imgs/weixin.png" alt="">
        <div class="form-item-title">微信</div>
        <wd-checkbox :model-value="selectedPaymentMethod === 'wechat'"
          @change="(checked) => handleCheckboxChange('wechat', checked)"></wd-checkbox>
      </div>

      <!-- 微信账户信息 -->
      <div v-if="selectedPaymentMethod === 'wechat' && withdrawAmount > 2000" class="form-item-card">
        <!-- 只有当提现金额大于2000时才显示姓名输入 -->
        <div v-if="withdrawAmount > 2000" class="wechat-name-input">
          <label class="input-label">微信姓名：</label>
          <input type="text" v-model="wechatRealName" placeholder="请输入微信实名认证姓名" class="name-input" maxlength="20" />
        </div>
        <div v-if="withdrawAmount > 2000" class="warning-tip">
          <div class="warning-icon">⚠️</div>
          <div class="warning-text">
            提现金额超过2000元，请务必填写微信实名认证的真实姓名，姓名不符将导致提现失败
          </div>
        </div>
      </div>


      <!-- <div class="form-item-card-btn" @click="goToAccountManage">
        账号不对，前往修改 <img src="../static//imgs//qianwng.png" alt="" srcset="">
      </div> -->
    </div>

    <!-- 提现说明 -->
    <div class="withdraw-notice">
      <div class="notice-title">提现说明</div>
      <div class="notice-content">
        <div class="notice-item">• 提现最低金额：{{ minWithdrawAmount }}元</div>
        <!-- <div class="notice-item">• 提现手续费：{{ feeRate }}%</div> -->
        <div class="notice-item">• 预计到账时间：{{ estimatedTime }}</div>
        <div class="notice-item">• 单日提现限额：{{ dailyLimit }}元</div>
        <div class="notice-item" v-if="userInfo.roleTypeId == 2">• 提现须知：入驻商家售出第一笔订单七天后，方可使用提现功能</div>
        <div class="notice-item" v-if="userInfo.roleTypeId == 2">• 每天晚21:00-24:00系统自动统计当日营业额，提交提现申请当日营业额不可提现。</div>
        <div class="notice-item" v-if="userInfo.roleTypeId == 1">• 提现须知：每天晚21:00-24：00系统自动统计当日配送额，提交提现申请当日配送额不可提现。</div>
      </div>
    </div>

    <!-- 底部占位区域，防止内容被固定按钮遮挡 -->
    <div class="bottom-placeholder"></div>

    <div class="btn" :class="{ 'btn-disabled': !canSubmit }" @click="submitWithdraw">
      {{ submitText }}
    </div>

    <!-- 加载遮罩 -->
    <wd-overlay v-model="loading" :close-on-click-overlay="false">
      <div class="loading-content">
        <wd-loading size="large" />
        <div class="loading-text">提交中...</div>
      </div>
    </wd-overlay>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import Return from '@/components/Return.vue'
// 获取用户数据
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()
// 响应式数据
const capsuleTop = ref(0)
const contentHeight = ref(0)
const selectedPaymentMethod = ref('wechat')
const withdrawAmountInput = ref('')
const withdrawAmount = ref(0)
const amountError = ref('')
const loading = ref(false)
const wechatRealName = ref('')

// 配置数据
const minWithdrawAmount = 1
const feeRate = 0.1
const dailyLimit = 50000
const estimatedTime = '1-3个工作日'

// 可提现金额
const availableAmount = ref(1000)

// 账户信息
const accountInfo = ref({
  wechat: {
    account: 'wx_123456',
    name: '张三'
  },
  alipay: {
    account: '15516544531',
    name: '邹小伟'
  },
  bank: {
    bankName: '中国银行',
    cardNumber: '6222021234567890123',
    name: '李四'
  }
})

// 计算属性
const canSubmit = computed(() => {
  return selectedPaymentMethod.value &&
    withdrawAmount.value >= minWithdrawAmount &&
    withdrawAmount.value <= fundInfo.value.availableFeeStr &&
    !amountError.value
})

const submitText = computed(() => {
  if (!selectedPaymentMethod.value) return '请选择提现方式'
  if (withdrawAmount.value < minWithdrawAmount) return `提现金额不能少于${minWithdrawAmount}元`
  if (withdrawAmount.value > availableAmount.value) return '提现金额不能超过可提现金额'
  return '提现申请'
})

const userInfo = ref({})

watch(() => userStore.customerInfo, (newVal) => {
  userInfo.value = newVal
}, {
  immediate: true,
  deep: true,
})


// 方法
const handlePaymentChange = (e) => {
  console.log('支付方式变更:', e)
}
const handleCheckboxChange = (method, checked) => {
  if (checked) {
    selectedPaymentMethod.value = method
  } else {
    selectedPaymentMethod.value = ''
  }
  console.log('支付方式变更:', method, checked)
}
const selectPaymentMethod = (method) => {
  selectedPaymentMethod.value = method
}

const handleAmountInput = (e) => {
  const value = e.detail.value
  // 只允许输入数字和小数点
  const filteredValue = value.replace(/[^\d.]/g, '')

  // 限制小数点后两位
  if (filteredValue.includes('.')) {
    const parts = filteredValue.split('.')
    if (parts[1].length > 2) {
      withdrawAmountInput.value = parts[0] + '.' + parts[1].substring(0, 2)
      return
    }
  }

  withdrawAmountInput.value = filteredValue
  withdrawAmount.value = parseFloat(filteredValue) || 0
  validateAmount()
}

const validateAmount = () => {
  amountError.value = ''

  if (!withdrawAmount.value) {
    amountError.value = '请输入提现金额'
    return
  }

  if (withdrawAmount.value < minWithdrawAmount) {
    amountError.value = `提现金额不能少于${minWithdrawAmount}元`
    return
  }

  if (withdrawAmount.value > fundInfo.value.availableFeeStr) {
    amountError.value = '提现金额不能超过可提现金额'
    return
  }

  if (withdrawAmount.value > dailyLimit) {
    amountError.value = `单日提现限额${dailyLimit}元`
    return
  }
}

const withdrawAll = () => {
  withdrawAmountInput.value = fundInfo.value.availableFeeStr.toString()
  withdrawAmount.value = fundInfo.value.availableFeeStr
  validateAmount()
}

const goToAccountManage = () => {
  uni.navigateTo({
    url: '/pages/Collection'
  })
}

const formatMoney = (amount) => {
  return (amount || 0).toFixed(2)
}

const maskBankCard = (cardNumber) => {
  if (!cardNumber) return ''
  return cardNumber.replace(/(\d{4})\d+(\d{4})/, '$1 **** **** $2')
}

const validateForm = () => {
  if (!withdrawAmount.value || withdrawAmount.value <= 0) {
    uni.showToast({
      title: '请输入有效的提现金额',
      icon: 'none'
    })
    return false
  }

  if (!selectedPaymentMethod.value) {
    uni.showToast({
      title: '请选择提现方式',
      icon: 'none'
    })
    return false
  }

  // 微信提现且金额大于2000时验证姓名
  if (selectedPaymentMethod.value === 'wechat' && withdrawAmount.value > 2000) {
    if (!wechatRealName.value || !wechatRealName.value.trim()) {
      uni.showToast({
        title: '提现金额超过2000元，请填写微信实名认证姓名',
        icon: 'none'
      })
      return false
    }

    // 简单的中文姓名格式验证
    const nameRegex = /^[\u4e00-\u9fa5]{2,10}$/
    if (!nameRegex.test(wechatRealName.value.trim())) {
      uni.showToast({
        title: '请输入正确的中文姓名',
        icon: 'none'
      })
      return false
    }
  }

  return true
}

const submitWithdraw = async () => {
  if (!validateForm()) return

  try {
    loading.value = true
    const userOpenId = JSON.parse(uni.getStorageSync('config-login'))
    console.log(userOpenId, 'userOpenId');

    // 构建请求参数
    const requestData = {
      amount: withdrawAmount.value,
      openid: userOpenId.openId,
      fundType: userInfo.value.roleTypeId == 1 ? 2: 1
    }

    // 如果是微信提现，添加实名姓名
    if (selectedPaymentMethod.value === 'wechat') {
      requestData.wechatRealName = wechatRealName.value.trim()
    }

    // 使用封装好的Fetch调用提现接口
    const res = await Fetch('shopping/pays/withdrawal', {
      method: 'POST',
      data: requestData
    })

    if (res.data.code === 200) {
      uni.showToast({
        title: '提现申请已提交',
        icon: 'success'
      })

      // 更新可提现金额
      // availableAmount.value -= withdrawAmount.value

      // // 清空输入
      // withdrawAmountInput.value = ''
      // withdrawAmount.value = 0
      // selectedPaymentMethod.value = ''
      // wechatRealName.value = '' // 清空微信姓名

      // if (wx.canIUse('requestMerchantTransfer')) {
      //   wx.requestMerchantTransfer({
      //     mchId: '1721949137',
      //     appId: wx.getAccountInfoSync().miniProgram.appId,
      //     package: res.data.data.packageInfo,
      //     success: (res) => {
      //       // res.err_msg将在页面展示成功后返回应用时返回ok，并不代表付款成功
      //       console.log('success:', res);
      //       fnFundInfo()
      //     },
      //     fail: (res) => {
      //       console.log('fail:', res);
      //       fnFundInfo()
      //     },
      //   });
      // } else {
      //   wx.showModal({
      //     content: '你的微信版本过低，请更新至最新版本。',
      //     showCancel: false,
      //   });
      // }

    } else {
      uni.showToast({
        title: res.data.msg || '提现申请提交失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('提现API调用失败:', error)
    uni.showToast({
      title: '提现失败，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

const fundInfo = ref({})

watch(()=>fundInfo.value, (newVal)=>{
  console.log(newVal, 'newVal');
})

// 个人基本账户查询
const fnFundInfo = async ()=>{
  const { status, data } = await Fetch('shopping/fund/getInfo', {
    method: 'get',
    data:{
      fundType:2
    }
  })
  if (status == 200 && data.code == 200){
    fundInfo.value = data.data
  } else {
    uni.showToast({
      title: data?.msg || '查询失败',
      icon: 'none'
    })
  }
  console.log( status, data , 'data');

}

onShow(()=>{
  fnFundInfo()
})

onMounted(() => {
  const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  capsuleTop.value = menuButtonInfo.bottom + 20
  contentHeight.value = wx.getSystemInfoSync().windowHeight - menuButtonInfo.bottom - 113
})

// 监听金额变化，当金额降到2000以下时清空微信姓名
watch(withdrawAmount, (newAmount) => {
  if (newAmount <= 2000) {
    wechatRealName.value = ''
  }
})
</script>

<style lang="scss">
.withdraw-cash-card {
  width: 670rpx;
  background: linear-gradient(266deg, #FFE97B 0%, #FECC3B 100%);
  border-radius: 20rpx 20rpx 20rpx 20rpx;
  padding: 30rpx;
  box-sizing: border-box;
  margin: 0 auto 40rpx;

  .card-title {
    font-weight: bold;
    font-size: 22rpx;
    color: #191919;
  }

  .card-priceStr {
    height: 72rpx;
    line-height: 72rpx;
    display: flex;
    align-items: center;
    font-weight: bold;
    font-size: 50rpx;
    color: #191919;
    margin-top: 10rpx;

    .priceStr-title {}
  }

  .card-freeze {
    height: 72rpx;
    line-height: 72rpx;
    display: flex;
    align-items: center;
    font-weight: bold;
    font-size: 22rpx;
    color: #191919;
    margin-top: 10rpx;

    .freeze-label {
      margin-right: 10rpx;
    }
  }

  .card-btn {
    margin-top: 40rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .card-btn-left {
      height: 32rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 22rpx;
      color: #191919;
      line-height: 32rpx;
    }

    .card-btn-right {
      font-weight: bold;
      font-size: 22rpx;
      color: #191919;
      line-height: 32rpx;
      cursor: pointer;
    }
  }
}

.page-line {
  width: 100%;
  height: 20rpx;
  background: #F5F5F5;
}

.withdraw-cash-tx {
  background: white;
  padding: 40rpx;
  box-sizing: border-box;

  .tx-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #191919;
    line-height: 40rpx;
    font-style: normal;
    margin-bottom: 34rpx;

    .tx-title-right {
      font-size: 24rpx;
      cursor: pointer;
      color: #007AFF;
    }

    .tx-title-left-value {
      font-weight: bold;
      font-size: 36rpx;
      color: #DF3A1B;
    }
  }

  .amount-error {
    color: #FF3B30;
    font-size: 24rpx;
    margin-top: 10rpx;
  }
}

.withdraw-cash-form {
  padding: 40rpx;

  .title {
    height: 40rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: bold;
    font-size: 28rpx;
    color: #191919;
    line-height: 40rpx;
    margin-bottom: 34rpx;
  }

  .form-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    cursor: pointer;

    image {
      width: 40rpx;
      height: 40rpx;
      margin-right: 16rpx;
    }

    .form-item-title {
      height: 40rpx;
      font-size: 28rpx;
      color: #191919;
      line-height: 40rpx;
      margin-right: auto;
    }
  }

  .form-item-card {
    width: 672rpx;
    min-height: 150rpx;
    background: #F5F5F5;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    margin-top: 24rpx;
    padding: 30rpx;
    font-weight: 400;
    font-size: 28rpx;
    color: #333333;
    box-sizing: border-box;

    .wechat-name-input {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      .input-label {
        font-size: 28rpx;
        color: #333;
        margin-right: 20rpx;
        min-width: 140rpx;
      }

      .name-input {
        flex: 1;
        height: 80rpx;
        padding: 0 20rpx;
        border: 1rpx solid #e5e5e5;
        border-radius: 8rpx;
        font-size: 28rpx;
        color: #333;
        background: #f8f8f8;

        &:focus {
          border-color: #fbe050;
          background: #fffbe6;
        }

        &::placeholder {
          color: #999;
          font-size: 26rpx;
        }
      }
    }

    .warning-tip {
      display: flex;
      align-items: flex-start;
      padding: 20rpx;
      background: #fff7e6;
      border: 1rpx solid #ffd591;
      border-radius: 8rpx;
      margin-top: 20rpx;

      .warning-icon {
        font-size: 28rpx;
        margin-right: 12rpx;
        margin-top: 2rpx;
      }

      .warning-text {
        flex: 1;
        font-size: 24rpx;
        color: #d46b08;
        line-height: 1.4;
      }
    }
  }

  .form-item-card-btn {
    font-size: 24rpx;
    color: #999999;
    margin-top: 14rpx;
    text-align: right;
    cursor: pointer;

    image {
      width: 10rpx;
      height: 19rpx;
    }
  }
}

.withdraw-notice {
  background: white;
  padding: 40rpx;
  // 移除 margin-bottom，因为现在有专门的占位区域

  .notice-title {
    font-weight: bold;
    font-size: 28rpx;
    color: #191919;
    margin-bottom: 20rpx;
  }

  .notice-content {
    .notice-item {
      font-size: 24rpx;
      color: #666666;
      line-height: 36rpx;
      margin-bottom: 10rpx;
    }
  }
}

.bottom-placeholder {
  height: 160rpx; // 按钮高度(100rpx) + 底部间距(30rpx) + 额外安全距离(30rpx)
  width: 100%;
}

.btn {
  width: 670rpx;
  height: 100rpx;
  line-height: 100rpx;
  background: #FBE050;
  border-radius: 50rpx 50rpx 50rpx 50rpx;
  font-weight: bold;
  font-size: 28rpx;
  color: #333333;
  text-align: center;
  font-style: normal;
  text-transform: none;
  position: fixed;
  bottom: 30rpx;
  left: 50%;
  transform: translateX(-50%);
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 999; // 确保按钮在最上层

  &.btn-disabled {
    background: #CCCCCC;
    color: #999999;
    cursor: not-allowed;
  }
}

.feedback-value {
  font-size: 24rpx;
  color: #999999;
  line-height: 90rpx;
  font-style: normal;
  text-transform: none;
  width: 100%;
  height: 90rpx;
  background: #F5F5F5;
  border-radius: 20rpx 20rpx 20rpx 20rpx;

  input {
    height: 90rpx;
    padding-left: 40rpx;
    width: calc(100% - 80rpx);
  }
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20rpx;
  padding: 60rpx;

  .loading-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #333333;
  }
}
</style>
